package cn.tedu.v1;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

/**
 * 聊天室 Version 1.1
 * 服务器 功能：1.服务器申请端口号：软件具备端口号
 *            2.在start方法中：等待客户端连接，返回socket
 *                           IO读入
 *     【新增】3.所有服务器端异常，全部捕获，明确提示
 *            4.关闭serverSocket
 * 测试：自己连接自己  测试
 */
public class Server {
    private ServerSocket serverSocket;
    private Server(){
        try {
            serverSocket=new ServerSocket(7777);
            //BindException  端口号已经被占用
        }catch (BindException e){
            System.out.println("请检查端口号，被占用~");
        }catch (SocketException e){
            System.out.println("连接重置或者断开");
        }  catch (IOException e) {
            System.out.println("客户端离开了");
        }
    }
    public void start(){
        BufferedReader br= null;
        Socket socket=null;
        try {
            System.out.println("等待客户端连接");
            socket=serverSocket.accept();
            System.out.println("一个客户端连接上了");
            InputStream is=socket.getInputStream();
            InputStreamReader isr=
                    new InputStreamReader(is,"UTF8");
            br = new BufferedReader(isr);
            while(true){
                String str=br.readLine();
                System.out.println("客户端："+str);
            }
        }catch (UnsupportedEncodingException e){
            System.out.println("请检查客户端/服务器端编码集：不一致");
        }catch (SocketException e){
            System.out.println("客户端链接被重置");
        } catch (IOException e) {
            System.out.println("客户端连接失效了");
        } finally {
            //关闭流 关闭socket
            if(br!=null)
                try {
                    br.close();
                } catch (IOException e) {
                    System.out.println("读入流断开链接");
                }
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("客户端socket断开连接~");
            }
        }
    }
    public static void main(String[] args){
        Server server=new Server();
            server.start();
        }
    }
